package deng.qiya.wechat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import deng.qiya.baidu.BaiduMap;
import deng.qiya.dao.CardTypeOper;
import deng.qiya.dao.ReplyMessageOper;
import deng.qiya.dao.TextMessageOper;
import deng.qiya.dao.WeChatHomeinnsUserOper;
import deng.qiya.model.BaiduGeocoderResult;
import deng.qiya.model.BaiduLocation;
import deng.qiya.model.TextMessage;
import deng.qiya.model.WeChatLocationMessage;
import deng.qiya.model.WeChatTextMessage;
import deng.qiya.util.WeChatMessageHelper;
import deng.qiya.util.XStreamMessageUtil;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	private TextMessageOper textMessageOper;
	
	@Autowired
	private TextMessageHandler textMessageHandler;
	
	@Autowired
	private ReplyMessageOper replyMessageOper;

	@Autowired
	private WeChatHomeinnsUserOper weChatHomeinnsUserOper;
	
	@Autowired
	private CardTypeOper cardTypeOper;
	
	@Autowired
	private BaiduMap baiduMap;
	
	@Autowired
	private WeChatMessageHelper weChatMessageHelper;
	/**
	 * wechat get request
	 * RequestParam(value="a", required=false) 
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	@ResponseBody
	public String homeCheck(String echostr, Model model) {
		String echo = "";
		try {
			echo = new String(echostr.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		logger.info("check message from wechat:"+ echo);
		//model.addAttribute("echostr", echo);
		return echo;
	}
	
	
	/**
	 *  wechat post handler
	 * @throws IOException 
	 */
	@RequestMapping(value = "/", method = RequestMethod.POST)
	@ResponseBody
	public String postHandler(HttpServletRequest request, Model model) throws IOException {
		
			String string = IOUtils.toString(request.getInputStream(),"utf-8");
			logger.info("wechat message from user:"+string);
			WeChatTextMessage textMessage = null;
			try{
				textMessage = XStreamMessageUtil.getWeChatTextMessage(string);
			}
			catch(Exception e){
			}
			
			if(textMessage != null){//text message handler
				String replyMessage = "";
				int textMessageId = textMessageOper.newTextMessage(TextMessage.convert2TextMessage(textMessage,Constant.QUESTION_TYPE_UNKNOW));//save message
				
				replyMessage = weChatMessageHelper.keyWordProccess(textMessage.getContent(), textMessage.getFromUserName());
				if(replyMessage != null && replyMessage.length() >0 ){
					logger.info(replyMessage);
					return replyMessage;
				}
				replyMessage = weChatMessageHelper.selectProccess(textMessage.getContent(), textMessage.getFromUserName(), textMessageId);
				
				if(replyMessage != null && replyMessage.length() >0 ){
					logger.info(replyMessage);
					return replyMessage;
				}

				BaiduGeocoderResult result = baiduMap.getPlace(textMessage.getContent());
				if(result != null&&result.getResult()!=null&&result.getResult().getLocation()!=null&&result.getResult().getLocation().getLat()!=null&&result.getResult().getLocation().getLat().length()>0) {
					replyMessage = weChatMessageHelper.mapLatLngProcess(result.getResult().getLocation(), textMessage.getFromUserName(), textMessageId);
				}
				if(replyMessage != null && replyMessage.length() >0 ){
					logger.info(replyMessage);
					return replyMessage;
				}
				
				logger.info(weChatMessageHelper.featureHintMessage(textMessage.getFromUserName()));
				return weChatMessageHelper.featureHintMessage(textMessage.getFromUserName());
			}
			
			
			
			WeChatLocationMessage locationMessage = null;
			locationMessage = XStreamMessageUtil.getWeChatLocationMessage(string);
			if(locationMessage != null){//location message handler
				String replyMessage = "";
				int textMessageId = textMessageOper.newTextMessage(TextMessage.convert2TextMessage(locationMessage,Constant.QUESTION_TYPE_UNKNOW));//save message
				replyMessage = weChatMessageHelper.mapLatLngProcess(new BaiduLocation(locationMessage.getLocationx(), locationMessage.getLocaltiony()), locationMessage.getFromUserName(), textMessageId);
				if(replyMessage!= null && replyMessage.length()>0){
					logger.info(replyMessage);
					return replyMessage;
					
				}
			}
			
			logger.info("no result, not text message or location message");
			return "";
	}
}
